/**
 * Created by huj09 on 2017/8/17.
 */

//绘制拖动点
function drawDragPoint(sprite) {

    //点所在位置
    var angle = ['lu', 'mu', 'ru', 'lm', 'rm', 'ld', 'md', 'rd'];
    // var cursorArr = ['nwse-resize', 'ns-resize', 'nesw-resize', 'ew-resize', 'ew-resize', 'nesw-resize', 'ns-resize', 'nwse-resize'];
    var spriteArr = [];
    for (var i = 0; i < 8; i++) {
        var point = new PIXI.Sprite.fromImage('css/img/point.png');
        point.angle = angle[i];
        point.type = 'dragPoint';
        point.visible = false;
        point.x = 0;
        point.parentSprite = sprite;
        point.y = 0;
        point.interactive = true;
        // point.cursor = 'pointer';
        bindPointDragEvent(point);
        stage.addChild(point);
        spriteArr.push(point);
    }
    sprite.dragPoint = spriteArr;
}

//设置选中
function setDragPoint(sprite, flag) {
    if (checkCtrlMode(sprite)) {
        sprite.filters = [outlineFilterDisable];
    } else {
        sprite.filters = [outlineFilter];
    }
    var x = sprite.x - sprite.width * sprite.anchor.x,
        y = sprite.y - sprite.height * sprite.anchor.y,
        width = sprite.width,
        height = sprite.height;
    var positionArr = [];
    x = x - 2;
    y = y - 2;
    positionArr.push({x: x, y: y - 2});
    positionArr.push({x: x + width / 2, y: y - 2});
    positionArr.push({x: x + width, y: y - 2});
    positionArr.push({x: x, y: y + height / 2});
    positionArr.push({x: x + width, y: y + height / 2});
    positionArr.push({x: x, y: y + height});
    positionArr.push({x: x + width / 2, y: y + height});
    positionArr.push({x: x + width, y: y + height});

    var isLock = checkCtrlMode(sprite);
    sprite.dragPoint.forEach(function (point, index) {
        // cancelSelectSprite(point);
        if (isLock) {
            point.texture = new PIXI.Texture.fromImage('css/img/unpoint.png');
        } else {
            point.texture = new PIXI.Texture.fromImage('css/img/point.png');
        }
        point.visible = flag;
        if (!flag) {
            sprite.filters = null;
        }
        point.alpha = 0.9;
        point.cursor = "wait";
        point.x = positionArr[index].x;
        point.y = positionArr[index].y;
    })
}

//绑定拖动点事件
function bindPointDragEvent(sprite) {
    sprite.on('mousedown', pointDragStart)
        .on('mouseup', pointDragEnd)
        .on('mouseupoutside', pointDragEnd)
        .on('mousemove', pointDragMove)
        .on('mouseover', pointOver);
}

function pointOver(event) {
    this.data = event.data;
    this.cursor = 'wait';
}

function checkCtrlMode(currSprite) {
    if (null === currSprite || currSprite === undefined || currSprite.ctrlMode === undefined) {
        return false;
    } else if (currSprite.ctrlMode) {
        return false;
    }
    return true;
}

function pointDragStart(event) {

    this.data = event.data;
    var newPosition = this.data.getLocalPosition(this.parent);
    this.kx = this.x;
    this.ky = this.y;
    var currSprite = this.parentSprite;
//        selectedObjct.currSel.interactive = false;
//        selectedObjct.currSel.anchor.set(0,0);
	var currAnchor = "lu";
	switch(this.angle){
		case "md":
		case "rm":
		case "rd":
			currAnchor = "lu";
			break;
		case "mu":
		case "ru":
			currAnchor = "ld";
			break;
		case "lu":
			currAnchor = "rd";
			break;
		case "lm":
			currAnchor = "ru";
			break;
	}
	changeAnchor(currSprite, currAnchor);
	if(selectedObjct.allSel.length>0){
		selectedObjct.allSel.forEach(function (cSprite, index) {
			changeAnchor(cSprite, currAnchor);
		});
	}else{
		changeAnchor(currSprite, currAnchor);
	}

    this.x = newPosition.x;
    this.y = newPosition.y;
    this.dragging = true;
}

function pointDragMove(event) {
    if (this.dragging) {
        this.data = event.data;
        var ctrlSprite = this.parentSprite;
        if (checkCtrlMode(ctrlSprite)) return;

        var newPosition = this.data.getLocalPosition(this.parent);
        this.x = newPosition.x;
        this.y = newPosition.y;

        var cx = this.x - this.kx, cy = this.y - this.ky;

        if (this.angle === 'lu') {
            cx = -cx;
            cy = -cy;
        } else if (this.angle === 'mu') {
            cx = 0;
            cy = -cy;
        } else if (this.angle === 'ru') {
            //cx = cx;
            cy = -cy;
        } else if (this.angle === 'rm') {
            //cx = cx;
            cy = 0;
        } else if (this.angle === 'rd') {
            //cx = cx;
            //cy = cy;
        } else if (this.angle === 'md') {
            cx = 0;
            //cy = cy;
        } else if (this.angle === 'ld') {
            cx = -cx;
            //cy = cy;
        } else if (this.angle === 'lm') {
            cx = -cx;
            cy = 0;
        }
        var offsetW = ctrlSprite.swidth + cx < 15 ? 15 : ctrlSprite.swidth + cx;
        var offsetH = ctrlSprite.sheight + cy < 15 ? 15 : ctrlSprite.sheight + cy;

        if (selectedObjct.allSel.length > 0) {
            selectedObjct.allSel.forEach(function (currSprite) {
                if(currSprite === ctrlSprite){
                    return true;
                }
                var otherOffsetW = currSprite.swidth + cx < 15 ? 15 : currSprite.swidth + cx;
                var otherOffsetH = currSprite.sheight + cy < 15 ? 15 : currSprite.sheight + cy;
                currSprite.width = Math.round(otherOffsetW);
                currSprite.height = Math.round(otherOffsetH);
                setDragPoint(currSprite, true);
            });
        }
        ctrlSprite.width = Math.round(offsetW);
        ctrlSprite.height = Math.round(offsetH);
        setDragPoint(ctrlSprite, true);
	}
}

function pointDragEnd(event) {
    this.data = event.data;
    this.dragging = false;
    this.data = null;
}


//设置原点
function changeAnchor(sprite, anpt) {
    var x = sprite.x - sprite.width * sprite.anchor.x;
    var y = sprite.y - sprite.height * sprite.anchor.y;
    //左上角设为原点
    if (anpt === "lu") {
        sprite.anchor.set(0, 0);
        sprite.x = x;
        sprite.y = y;
    } else if (anpt === "ru") {
        sprite.anchor.set(1, 0);
        sprite.x = x + sprite.width;
        sprite.y = y;
    } else if (anpt === "rd") {
        sprite.anchor.set(1, 1);
        sprite.x = x + sprite.width;
        sprite.y = y + sprite.height;
    } else if (anpt === "ld") {
        sprite.anchor.set(0, 1);
        sprite.x = x;
        sprite.y = y + sprite.height;
    }
    sprite.swidth = sprite.width;
    sprite.sheight = sprite.height;
}

function onClickSprite(event) {
    this.data = event.data;
    this.shader = 1;
}


function bindDraggingEvent(sprite) {
    sprite.on('mousedown', onDragStart)
        .on('mouseup', onDragEnd)
        .on('mouseupoutside', onDragEnd)
        .on('mousemove', onDragMove);
}

function onDragStart(event) {
    this.data = event.data;
    if (chop.chopping) {
        chopImg(this.data.getLocalPosition(this.parent));
        graphics.clear();
        chop.chopping = false;
        chop.chopInPic = true;
        return;
    }

    var newPosition = this.data.getLocalPosition(this.parent);
    //设置原点为鼠标所在位置
    var testW = ((newPosition.x - this.x + this.width * this.anchor.x) / this.width).toFixed(4);
    var testH = ((newPosition.y - this.y + this.height * this.anchor.y) / this.height).toFixed(4);
    this.anchor.set(testW, testH);
    this.x = newPosition.x;
    this.y = newPosition.y;
    selectedObjct.bgdg_x = this.x - this.width * testW;
    selectedObjct.bgdg_y = this.y - this.height * testH;
    //this.alpha = 0.5;
    this.dragging = true;

    //按下ctrl键时
    if (ctrlPress) {
        //当前操作之前非多选
        if (selectedObjct.allSel.length === 0) {
            //之前未选中任何sprite
            if (selectedObjct.currSel === null) {
                //设置sprite为当前选中
                if (!selectCombWithCtrl(this)) {
                    selectedObjct.currSel = this;
                }
            } else {//之前已选中一个sprite
                if (selectedObjct.currSel !== this) {
                    selectedObjct.allSel.push(selectedObjct.currSel);
                    selectedObjct.currSel = null;
                    if (!selectCombWithCtrl(this)) {
                        selectedObjct.allSel.push(this);
                    }
                }
            }
            selectSprite(this);
        } else { //当前操作之前是多选
            //当前对象不在多选中 -- 执行添加 否则 执行删除
            if (selectedObjct.allSel.indexOf(this) === -1) {
                //如果当前sprite不在组合中
                if (!selectCombWithCtrl(this)) {
                    selectedObjct.allSel.push(this);
                    selectSprite(this);
                }
            } else {
                if (!cancelSelectCombWithCtrl(this)) {
                    var index = selectedObjct.allSel.indexOf(this);
                    cancelSelectSprite(this);
                    selectedObjct.allSel.splice(index, 1);
                }
            }
        }
    } else { //未按下ctrl键
        //如果当前sprite不在多选中
        if (selectedObjct.allSel.indexOf(this) === -1) {
            //撤销上一个单独选中
            if (null !== selectedObjct.currSel) {
                cancelSelectSprite(selectedObjct.currSel)
            }
            selectedObjct.currSel = this;
            selectSprite(this);
            //清除之前的多选
            selectedObjct.allSel.forEach(function (obj) {
                obj.filters = null;
                setDragPoint(obj, false)
            });
            selectedObjct.allSel = [];
            //组合 选中
            selectComb(this);
        }
    }
}

function onDragEnd() {
    bkg.dragging = false;
    //框选
    if (graphics.graphicsData[0] && graphics.graphicsData[0].shape) {
        recSelect(graphics.graphicsData[0].shape);
    }
    graphics.clear();
    this.alpha = 1;
    this.dragging = false;
    this.data = null;

    if (selectedObjct.allSel.length > 0) {
        selectedObjct.allSel.forEach(function (sprite) {
            sprite.alpha = 1;
            sprite.sx = sprite.x;
            sprite.sy = sprite.y;
        })
    }
}

function onDragMove() {

    if (this.dragging) {
        if (checkCtrlMode(this)) return;
        this.alpha = 0.5;
        var newPosition = this.data.getLocalPosition(this.parent);
        this.x = newPosition.x;
        this.y = newPosition.y;

        setDragPoint(this, true);

        var py_x = this.x - this.anchor.x * this.width - selectedObjct.bgdg_x;
        var py_y = this.y - this.anchor.y * this.height - selectedObjct.bgdg_y;

        var yspt = this;
        if (selectedObjct.allSel.length > 0) {
            selectedObjct.allSel.forEach(function (sprite) {
                if (yspt !== sprite) {
                    if (checkCtrlMode(sprite)) {
                        //取消选中锁定的sprite
                        cancelSelectSprite(sprite);
                        return true;
                    }
                    sprite.alpha = 0.5;
                    sprite.x = sprite.sx + py_x;
                    sprite.y = sprite.sy + py_y;
                    setDragPoint(sprite, true);
                }
            })
        }
    }
}

function drawChopLine(mousePos) {

    graphics.clear();
    graphics.lineStyle(1, 0x66ccff, 0.8);

    graphics.moveTo(0, mousePos.y);
    graphics.lineTo(1024, mousePos.y);

    graphics.moveTo(mousePos.x, 0);
    graphics.lineTo(mousePos.x, 680);

    stage.addChild(graphics);
}

//图片切割
function chopImg(mPos) {

    var sprite = selectedObjct.currSel;

    var shape = getStandardShape(sprite);
    shape.x = Math.round(sprite.x - sprite.anchor.x * sprite.width);
    shape.y = Math.round(sprite.y - sprite.anchor.y * sprite.height);
    var vFlag = false, hFlag = false;

    if (mPos.x >= shape.x && mPos.x <= (shape.x + shape.width)) {
        vFlag = true;
    }

    if (mPos.y >= shape.y && mPos.y <= (shape.y + shape.height)) {
        hFlag = true;
    }

    if (!vFlag && !hFlag) {
        return;
    }

    var scale_x = sprite.scale.x;
    var scale_y = sprite.scale.y;

    var texture1 = sprite.texture.clone();
    var texture2 = sprite.texture.clone();

    var tx = sprite.texture.frame.x || 0,
        ty = sprite.texture.frame.y || 0;

    var x1, y1, width1, height1, x2, y2, width2, height2;

    var rectangle1;
    var rectangle2;

    var s1;
    var s2;

    if (vFlag && hFlag) {

        var texture3 = sprite.texture.clone();
        var texture4 = sprite.texture.clone();

        var x3, y3, width3, height3, x4, y4, width4, height4;

        x1 = tx;
        y1 = ty;
        width1 = Math.round((mPos.x - shape.x) / scale_x);
        height1 = Math.round((mPos.y - shape.y) / scale_y);

        x2 = Math.round(tx + (mPos.x - shape.x) / scale_x);
        y2 = ty;
        width2 = Math.round(shape.width / scale_x - width1);
        height2 = height1;

        x3 = tx;
        y3 = Math.round(ty + (mPos.y - shape.y) / scale_y);
        width3 = width1;
        height3 = Math.round(shape.height / scale_y - height1);

        x4 = x2;
        y4 = y3;
        width4 = width2;
        height4 = height3;

        rectangle1 = new PIXI.Rectangle(x1, y1, width1, height1);
        rectangle2 = new PIXI.Rectangle(x2, y2, width2, height2);

        var rectangle3 = new PIXI.Rectangle(x3, y3, width3, height3);
        var rectangle4 = new PIXI.Rectangle(x4, y4, width4, height4);

        texture1.frame = rectangle1;
        texture2.frame = rectangle2;

        texture3.frame = rectangle3;
        texture4.frame = rectangle4;

        s1 = new PIXI.Sprite(texture1);
        s2 = new PIXI.Sprite(texture2);
        var s3 = new PIXI.Sprite(texture3);
        var s4 = new PIXI.Sprite(texture4);

        s1.anchor.set(0, 0);
        s2.anchor.set(0, 0);
        s3.anchor.set(0, 0);
        s4.anchor.set(0, 0);

        s1.scale.set(scale_x, scale_y);
        s2.scale.set(scale_x, scale_y);
        s3.scale.set(scale_x, scale_y);
        s4.scale.set(scale_x, scale_y);

        s1.x = shape.x;
        s1.y = shape.y;

        s2.x = s1.x + s1.width;
        s2.y = s1.y;

        s3.x = s1.x;
        s3.y = s1.y + s1.height;

        s4.x = s1.x + s1.width;
        s4.y = s1.y + s1.height;

        var stArr = [];
        stArr.push(s1);
        stArr.push(s2);
        stArr.push(s3);
        stArr.push(s4);

        stArr.forEach(function(sprite){
            sprite.sx = sprite.x;
            sprite.sy = sprite.y;
            sprite.interactive = true;
            sprite.buttonMode = true;
            bindDraggingEvent(sprite);
            stage.addChild(sprite);
            drawDragPoint(sprite);
            selectedObjct.allSel.push(sprite);
            selectSprite(sprite);
        })
        selectedObjct.currSel = null;
        removeSprite(sprite);
    } else if (vFlag || hFlag) {
        if (vFlag) {
            x1 = tx;
            y1 = ty;
            width1 = Math.round((mPos.x - shape.x) / scale_x);
            height1 = Math.round(shape.height / scale_y);

            x2 = Math.round(tx + width1);
            y2 = ty;
            width2 = Math.round(shape.width / scale_x - width1);
            height2 = height1;
        }
        if (hFlag) {
            x1 = tx;
            y1 = ty;
            width1 = Math.round(shape.width / scale_x);
            height1 = Math.round((mPos.y - shape.y) / scale_y);

            x2 = tx;
            y2 = Math.round(ty + (mPos.y - shape.y) / scale_y);
            width2 = width1;
            height2 = Math.round(shape.height/scale_y - height1);
        }
        rectangle1 = new PIXI.Rectangle(x1, y1, width1, height1);
        rectangle2 = new PIXI.Rectangle(x2, y2, width2, height2);

        texture1.frame = rectangle1;
        texture2.frame = rectangle2;

        s1 = new PIXI.Sprite(texture1);
        s2 = new PIXI.Sprite(texture2);

        s1.anchor.set(0, 0);
        s2.anchor.set(0, 0);

        s1.x = shape.x;
        s1.y = shape.y;

        s1.scale.set(scale_x, scale_y);
        s2.scale.set(scale_x, scale_y);

        if (vFlag) {
            s2.x = s1.x + s1.width;
            s2.y = s1.y;
        } else if (hFlag) {
            s2.x = s1.x;
            s2.y = s1.y + s1.height;
        }

        var stArr = [];
        stArr.push(s1);
        stArr.push(s2);

        stArr.forEach(function(sprite){
            sprite.sx = sprite.x;
            sprite.sy = sprite.y;
            sprite.interactive = true;
            sprite.buttonMode = true;
            bindDraggingEvent(sprite);
            stage.addChild(sprite);
            drawDragPoint(sprite);
            selectedObjct.allSel.push(sprite);
            selectSprite(sprite);
        })
        selectedObjct.currSel = null;
        removeSprite(sprite);
    }
}

//组合记录（存放组合数组）
var combineArr = [];
//当前选中的组合
var curComb = [];
//组合
function combine() {
    var tpArr = [];
    selectedObjct.allSel.forEach(function (sprite) {
        tpArr.push(sprite);
    });
    if (tpArr.length > 1 && !isCombineExist(tpArr)) {
        combineArr.push(tpArr);
    }
}

//是否组合已存在
function isCombineExist(saArr) {
    var exsitFlag = false;
    var tempFlag = true;
    for (var i = 0; i < combineArr.length; i++) {
        if (combineArr[i].length === saArr.length) {
            tempFlag = true;
            for (var j = 0; j < saArr.length; j++) {
                if (combineArr[i].indexOf(saArr[j]) === -1) {
                    tempFlag = false;
                }
            }
            if (tempFlag) {
                exsitFlag = true;
                break;
            }
        }
    }
    return exsitFlag;
}

//取消组合
function cancelCombine() {
    var index = combineArr.indexOf(curComb);
    combineArr.splice(index, 1);
    curComb = [];
}

//选择(组合判断)
function selectComb(sprite) {
    var flag = false;
    combineArr.forEach(function (arr) {
        if (arr.indexOf(sprite) > -1) {
            flag = true;
            curComb = arr;
            selectedObjct.currSel = null;
            selectedObjct.allSel = [].concat(arr);
            selectedObjct.allSel.forEach(function (spt) {
                selectSprite(spt);
            })
        }
    });
    return flag;
}

//选择(组合判断)+CTRL
function selectCombWithCtrl(sprite) {
    var flag = false;
    combineArr.forEach(function (arr) {
        if (arr.indexOf(sprite) > -1) {
            flag = true;
            curComb = arr;
            selectedObjct.currSel = null;
            selectedObjct.allSel = selectedObjct.allSel.concat(arr);
            selectedObjct.allSel.forEach(function (spt) {
                selectSprite(spt);
            })
        }
    });
    return flag;
}


//取消选择(组合判断)+ CTRL

function cancelSelectCombWithCtrl(sprite) {
    var flag = false;
    combineArr.forEach(function (arr) {
        if (arr.indexOf(sprite) > -1) {
            flag = true;
            arr.forEach(function (spt) {
                var index = selectedObjct.allSel.indexOf(spt);
                cancelSelectSprite(spt);
                selectedObjct.allSel.splice(index, 1);
            })
        }
    });
    return flag;
}

//删除sprite
function removeSprite(sprite) {
    sprite.dragPoint.forEach(function (point) {
        stage.removeChild(point);
    });
    stage.removeChild(sprite);
}

//选中sprite
function selectSprite(sprite) {
    setDragPoint(sprite, true);
}

//清除 选中sprite
function cancelSelectSprite(sprite) {
    sprite.filters = null;
    setDragPoint(sprite, false);
}